#!/usr/bin/env sh
set -eu

# FastAPI dev server launcher (Linux): start server and open browser
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJ_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJ_ROOT"

TEST_URL="http://127.0.0.1:8000/"
LOG_FILE=".uvicorn.log"

test_server() {
  curl -fsS --max-time 1 "$TEST_URL" >/dev/null 2>&1
}

open_browser() {
  if command -v xdg-open >/dev/null 2>&1; then
    xdg-open "$TEST_URL" >/dev/null 2>&1 || true
  else
    # Fallback to Python webbrowser if xdg-open is unavailable
    python - <<'PY' || true
import webbrowser
webbrowser.open("http://127.0.0.1:8000/")
PY
  fi
}

if test_server; then
  printf "%s\n" "Server is already running. Opening browser..."
  open_browser
  exit 0
fi

printf "%s\n" "Starting FastAPI dev server..."
nohup python -m uvicorn server:app --reload > "$LOG_FILE" 2>&1 &
PID=$!

# Wait for server to come up (max 15s)
MAX_WAIT=15
ELAPSED=0
while ! test_server && [ "$ELAPSED" -lt "$MAX_WAIT" ]; do
  sleep 1
  ELAPSED=$((ELAPSED+1))
done

if test_server; then
  printf "%s\n" "Server ready. Opening browser..."
  open_browser
  exit 0
else
  printf "%s\n" "Server failed to start within timeout. Check $LOG_FILE"
  tail -n 50 "$LOG_FILE" 2>/dev/null || true
  exit 1
fi